<script lang="ts" setup>
import { reactive, ref, watch } from "vue"
import {
  createUserDataApi,
  deleteUserDataApi,
  updateUserDataApi,
  getUserDataApi,
  getdepartement,
  disabledUser
} from "@/api/user"
import { type IGetUserData } from "@/api/user/types/user"
import { type FormInstance, type FormRules, ElMessage, ElMessageBox } from "element-plus"
import { Search, Refresh, CirclePlus, RefreshRight } from "@element-plus/icons-vue"
import { usePagination } from "@/hooks/usePagination"
import { useAuthStore } from "@/store/modules/auth"
import { useUserStore } from "@/store/modules/user"
import { useTeamStore } from "@/store/modules/team"
import { useDepartmentStore } from "@/store/modules/department"
import { formatDateTime } from "@/utils"

defineOptions({
  name: "userList"
})

const loading = ref<boolean>(false)
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()
const authStore = useAuthStore()
const departmentStore = useDepartmentStore()
// 用户
const userStore = useUserStore()
// console.log(userStore.usernameID, 333333)

const userNameAd = ref(false)
if (Number(userStore.usernameID) == 1 || userStore.roles.join() === "子账户超级管理员") {
  userNameAd.value = true
}
/**团队列表 */
const teamList = ref<any>([])
/** 权限列表持久化读取 */
const roleList = ref<any>([])
// 部门持久化读取
const teamListA = ref<any>([])
// ***************************===============================================================*******************
//#region 增
const dialogVisible = ref<boolean>(false)
const formRef = ref<FormInstance | null>(null)
const formData = reactive({
  name: "",
  password: "",
  team: "",
  role: "",
  roleList: [],
  dyIdList: [], // 抖音
  teams: "",
  nickName: "",
  source: "",
  department: "",
  maxOrder: 0,
  imei: ""
})

const formRules: FormRules = reactive({
  name: [{ required: true, trigger: "blur", message: "请输权限名称" }],
  maxOrder: [{ required: true, trigger: "blur", message: "请输入" }],
  password: [{ required: true, trigger: "blur", message: "请输密码" }]
})
const handleCreate = () => {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      if (currentUpdateId.value === undefined) {
        createUserDataApi({
          name: formData.name,
          password: formData.password,
          team: formData.team || userStore.teamName,
          role: formData.role,
          roleList: formData.roleList,
          nickName: formData.nickName,
          department: formData.department || userStore.department,
          maxOrder: formData.maxOrder || userStore.usermaxOrder,
          dyIdList: formData.dyIdList,
          imei: formData.imei
        }).then(() => {
          ElMessage.success("新增成功")
          dialogVisible.value = false
          getTableData()
        })
      } else {
        updateUserDataApi({
          id: currentUpdateId.value,
          name: formData.name,
          password: formData.password,
          team: formData.team,
          role: formData.role,
          roleList: formData.roleList,
          nickName: formData.nickName,
          department: formData.department,
          maxOrder: formData.maxOrder,

          dyIdList: formData.dyIdList,
          imei: formData.imei
        }).then(() => {
          ElMessage.success("修改成功")
          dialogVisible.value = false
          getTableData()
        })
      }
    } else {
      return false
    }
  })
}
const resetForm = () => {
  currentUpdateId.value = undefined
  clearValidate()
  formData.name = ""
  formData.password = ""
  formData.department = ""
  formData.team = ""
  formData.teams = ""
  formData.role = ""
  formData.nickName = ""
  formData.maxOrder = 0
  formData.imei = ""
}
//#endregion

//#region 删
const handleDelete = (row: IGetUserData) => {
  ElMessageBox.confirm(`正在删除用户：${row.name}，确认删除？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    deleteUserDataApi(row.id).then(() => {
      ElMessage.success("删除成功")
      getTableData()
    })
  })
}
//#endregion

//#region 改
const currentUpdateId = ref<undefined | string>(undefined)
const handleUpdate = (row: any) => {
  console.log(row, 888888)
  currentUpdateId.value = row.id
  formData.name = row.name
  formData.teams = row.roleList
  formData.password = row.password
  formData.role = row.role
  formData.team = row.team
  formData.roleList = row.roleList
  formData.nickName = row.nickName
  formData.department = row.department
  formData.maxOrder = row.maxOrder
  formData.imei = row.imei
  formData.dyIdList = row.dyIdList
  dialogVisible.value = true
  if (formData.department) {
    teamListA.value.forEach((item: any) => {
      if (item.name === formData.department) {
        getdepartement({
          page: paginationData.currentPage,
          size: paginationData.pageSize,
          id: item.id
        }).then((res: any) => {
          console.log(res, "筛选的团队")
          teamList.value = res.data
        })
      }
    })
  } else {
    formData.team = ""
    teamList.value = []
  }
}
//#endregion

//#region 查
const tableData = ref<IGetUserData[]>([])
const searchFormRef = ref<FormInstance | null>(null)
const searchData = reactive({
  name: "",
  team: "",
  role: "",
  nickName: "" //归属部门
})
const getTableData = () => {
  loading.value = true
  getUserDataApi({
    page: paginationData.currentPage,
    size: paginationData.pageSize,
    name: searchData.name || undefined,
    role: searchData.role || "",
    department: userStore.department || "" || searchData.nickName,
    team: userStore.teamName || searchData.team,
    maxOrder: userStore.usermaxOrder
  })
    .then((res) => {
      paginationData.total = res.data.total
      tableData.value = res.data.userList
      console.log(res.data.userList, "用户数据")
      console.log(userStore.usermaxOrder, "账号信息回显")
    })
    .catch(() => {
      tableData.value = []
    })
    .finally(() => {
      loading.value = false
    })
}
const handleSearch = () => {
  if (paginationData.currentPage === 1) {
    getTableData()
  }
  paginationData.currentPage = 1
}
const resetSearch = () => {
  searchFormRef.value?.resetFields()
  if (paginationData.currentPage === 1) {
    getTableData()
  }
  paginationData.currentPage = 1
}
const handleRefresh = () => {
  getTableData()
}
//#endregion

// #region 根据部门查团队
const changeDepartment = (val: any) => {
  if (val) {
    teamListA.value.forEach((item: any) => {
      if (item.name === val) {
        getdepartement({
          page: paginationData.currentPage,
          size: paginationData.pageSize,
          id: item.id
        }).then((res: any) => {
          console.log(res, "筛选的团队")
          teamList.value = res.data
          formData.team = ""
          formData.roleList = []
        })
      }
    })
  } else {
    formData.team = ""
    teamList.value = []
  }
}
// #endregion
/**账号禁用启用 */
const handleDisabled = (row: any) => {
  ElMessageBox.confirm(
    `正在${row.del ? "启用" : "禁用"}用户：${row.name}，确认${row.del ? "启用" : "禁用"}？`,
    "提示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    }
  ).then(() => {
    disabledUser({ id: row.id, del: row.del ? 0 : 1 }).then((res: any) => {
      if (res.code == 200) ElMessage.success("操作成功")
      getTableData()
    })
  })
}
const tableRowClassName = (row: any) => {
  if (row.row.del == 1) {
    return "warning-row"
  }
  return ""
}

// #region 监听分页参数的变化
watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, { immediate: true })
/**监听权限缓存数据（pinia） */
authStore.getAuthFn()
watch(
  [() => authStore.authListStore],
  (newValue) => {
    roleList.value = newValue.flat()
  },
  {
    immediate: true
  }
)
/**监听部门数据缓存（pinia) */
// departmentStore.getDepartmentFn()
// watch(
//   [() => departmentStore.departmentListStore],
//   (newValue) => {
//     teamListA.value = newValue.flat()
//     changeDepartment(userStore.department)
//   },
//   {
//     immediate: true
//   }
// )
import { getDepartment } from "@/api/team"
const getDepartmentFn = async () => {
  await getDepartment({
    page: 1,
    size: 1000
  }).then((res: any) => {
    teamListA.value = res.data.list

    console.log(teamListA.value, "接口的部门")
  })
}
getDepartmentFn()
// #endregion

// #region 清除规则报错信息
const clearValidate = () => {
  formRef.value?.clearValidate()
}
// #endregion

// 先获取用户信息 如果他有部门有团队那么渲染出来的不能更改
// 如果有部门没有团队那么添加的时候可以选择部门下的团队
console.log(userStore.teamName, "获取账户的团队数据")

// #region 查找团队和部门下拉框
const TeamListArr = ref()
const departmentListArr = ref()
const teamStore = useTeamStore()
departmentListArr.value = departmentStore.departmentListStore
/**监听 team 缓存 */
teamStore.getTeamFn()
watch(
  [() => teamStore.teamListStore],
  (newValue) => {
    TeamListArr.value = newValue.flat()
    // teamList.value = [...teamList.value, ...newValue.flat()]
  },
  {
    immediate: true
  }
)
/**team END */

// #region 抖音配置
import { getDyLive } from "@/api/order"
const dyLive = ref<any>([])
const getDy = () => {
  getDyLive({
    page: 1,
    size: 100
  })
    .then((res) => {
      console.log(res)
      dyLive.value = res.data.map((item: any) => {
        return {
          dyName: `${item.dyId}-${item.dyName}`,
          dyId: item.dyId
        }
      })
    })
    .catch(() => {
      dyLive.value = []
    })
}
getDy()
// #endregion
</script>

<template>
  <div class="app-container">
    <el-card v-loading="loading" shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="name" label="用户名">
          <el-input v-model.trim="searchData.name" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="role" label="权限名">
          <el-input v-model.trim="searchData.role" placeholder="请输入权限关键字" />
        </el-form-item>
        <el-form-item prop="nickName" label="归属部门">
          <el-select v-model="searchData.nickName" clearable filterable placeholder="请选择归属部门">
            <el-option v-for="item in departmentListArr" :key="item.id" :label="item.name" :value="item.name" />
          </el-select>
        </el-form-item>
        <el-form-item prop="team" label="归属团队">
          <el-select v-model="searchData.team" clearable filterable placeholder="请选择归属团队">
            <el-option v-for="item in TeamListArr" :key="item.id" :label="item.name" :value="item.name" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card v-loading="loading" shadow="never">
      <div class="toolbar-wrapper">
        <div>
          <el-button type="primary" :icon="CirclePlus" @click="dialogVisible = true">添加账户</el-button>
          <!-- <el-button type="danger" :icon="Delete">批量删除</el-button> -->
        </div>
        <div>
          <!-- <el-tooltip content="下载">
            <el-button type="primary" :icon="Download" circle />
          </el-tooltip> -->
          <el-tooltip content="刷新表格">
            <el-button type="primary" :icon="RefreshRight" circle @click="handleRefresh" />
          </el-tooltip>
        </div>
      </div>
      <div class="table-wrapper">
        <el-table :data="tableData" :row-class-name="tableRowClassName">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column prop="id" label="ID" align="center" />
          <el-table-column prop="createTime" label="创建时间" align="center">
            <template #default="scope">
              {{ formatDateTime(scope.row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="nickName" label="昵称" align="center" />
          <el-table-column prop="name" label="用户名" align="center" />
          <el-table-column prop="department" label="归属部门" align="center" />
          <el-table-column prop="team" label="归属团队" align="center" />
          <el-table-column prop="role" label="权限" align="center" />
          <!-- <el-table-column prop="password" label="密码" align="center" /> -->
          <el-table-column prop="money" label="账户余额" align="center" />
          <el-table-column prop="imei" label="外呼配置" align="center" />
          <el-table-column fixed="right" label="操作" width="150" align="center">
            <template #default="scope">
              <el-button
                :disabled="scope.row.del == 1"
                type="primary"
                text
                bg
                size="small"
                @click="handleUpdate(scope.row)"
                >修改</el-button
              ><br />
              <el-button type="primary" text bg size="small" style="margin: 10px 0" @click="handleDisabled(scope.row)">
                <span>{{ scope.row.del ? "启用" : "禁用" }}</span> </el-button
              ><br />
              <el-button
                type="danger"
                v-if="userStore.roles[0] == '超级管理员' || userStore.roles[0] == '管理账户'"
                text
                bg
                size="small"
                @click="handleDelete(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pager-wrapper">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- 新增/修改 -->
    <el-dialog
      v-model="dialogVisible"
      :title="currentUpdateId === undefined ? '新增用户' : '修改用户'"
      @close="resetForm"
      width="30%"
    >
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" label-position="left">
        <el-form-item prop="nickName" label="昵称">
          <el-input v-model="formData.nickName" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="name" label="账号">
          <el-input v-model="formData.name" placeholder="请输入" :disabled="currentUpdateId != undefined" />
        </el-form-item>
        <el-form-item prop="password" label="密码">
          <el-input v-model="formData.password" placeholder="请输入" type="password" />
        </el-form-item>
        <el-form-item label="部门" prop="department" v-if="userStore.department == ''">
          <el-select
            v-model="formData.department"
            @change="changeDepartment"
            clearable
            placeholder="请选部门"
            style="width: 100%"
          >
            <el-option v-for="item in teamListA" :key="item.id" :label="item.name" :value="item.name" />
          </el-select>
        </el-form-item>
        <el-form-item label="部门" prop="department" v-else>
          <el-input v-model="userStore.department" disabled />
        </el-form-item>
        <el-form-item prop="team" label="团队" v-if="userStore.teamName == ''">
          <el-select v-model="formData.team" clearable placeholder="请选团队" style="width: 100%" filterable>
            <el-option v-for="item in teamList" :key="item.id" :label="item.name" :value="item.name" />
          </el-select>
        </el-form-item>
        <el-form-item prop="team" label="团队" v-else>
          <el-input v-model="userStore.teamName" disabled />
        </el-form-item>
        <!--  -->
        <el-form-item
          prop="roleList"
          label="多团队数据"
          v-if="userStore.roles[0] == '超级管理员' || userStore.roles[0] == '管理账户'"
        >
          <el-select
            clearable
            filterable
            multiple
            v-model="formData.roleList"
            placeholder="请选择部门在选择团队，可多选，用于跨团队数据查看"
            style="width: 100%"
          >
            <el-option v-for="item in TeamListArr" :key="item.id" :label="item.name" :value="item.name" />
            <!-- <el-option v-for="item in teamList" :key="item.id" :label="item.name" :value="item.name" /> -->
          </el-select>
        </el-form-item>
        <!-- 渲染不同权限列表 -->
        <el-form-item v-if="userNameAd" prop="powerList" label="权限">
          <el-select v-model="formData.role" clearable placeholder="请选权限" filterable style="width: 100%">
            <el-option v-for="item in roleList" :key="item.id" :label="item.name" :value="item.name" />
          </el-select>
        </el-form-item>
        <el-form-item v-else prop="powerList" label="权限">
          <el-select v-model="formData.role" clearable placeholder="请选权限" filterable style="width: 100%">
            <el-option value="文员" />
            <el-option value="售后客服" />
            <el-option value="新媒体-业务员" />
            <el-option value="拼多多文员" />
            <el-option value="天猫平台文员" />
            <el-option value="京东平台文员" />
            <el-option value="抖音小店文员" />
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="userStore.department !== '' && userStore.teamName !== ''"
          prop="maxOrder"
          label="信息添加数量"
        >
          <el-input v-model.number="userStore.usermaxOrder" placeholder="请输入" disabled />
        </el-form-item>
        <el-form-item v-else prop="maxOrder" label="信息添加数量">
          <el-input v-model.number="formData.maxOrder" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="imei" label="外呼配置">
          <el-input v-model.number="formData.imei" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="dyIdList" label="抖音配置">
          <el-select
            clearable
            filterable
            multiple
            v-model="formData.dyIdList"
            placeholder="请选择抖音直播间id"
            style="width: 100%"
          >
            <el-option v-for="item in dyLive" :key="item.dyId" :label="item.dyName" :value="item.dyId" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreate">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;
  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}

.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}
</style>
<style>
.el-table .warning-row {
  color: #ccc;
}
</style>
